using System.Linq;
using ECatalog.Controllers;

namespace ECatalog.Models.UserModel
{
    public class UserRepository : IUserRepository
    {
        public User Save(User user)
        {
            var usr = new User
                {
                    Login = user.Login,
                    IsAdmin = user.IsAdmin,
                    Password = AppHelper.HashAndSolt(user.Password)
                };
            using (var db = new DbContainer())
            {
                db.Users.Add(usr);
                db.SaveChanges();
            }
            return usr;
        }

        public User GetUserByLogin(string login)
        {
            using (var db = new DbContainer())
            {
                return db.Users.FirstOrDefault(user => user.Login.ToLower() == login);
            }
        }

        public bool ExistUserByLogin(string login)
        {
            using (var db = new DbContainer())
            {
                var usr = db.Users.FirstOrDefault(user => user.Login.ToLower() == login);
                return usr != null;
            }
        }

        public User[] GetAllUsers()
        {
            using (var db = new DbContainer())
            {
                return db.Users.ToArray();
            }
        }

        public User GetUserById(int id)
        {
            using (var db = new DbContainer())
            {
                return db.Users.FirstOrDefault(u => u.UserId == id);
            }
        }

        public void RemoveUserById(int id)
        {
            using (var db = new DbContainer())
            {
                var user = db.Users.FirstOrDefault(u => u.UserId == id);
                if (user != null)
                {
                    db.Users.Remove(user);
                    db.SaveChanges();
                }
            }
        }

        public bool IsAdmin(string name)
        {
            using (var db = new DbContainer())
            {
                var user = db.Users.FirstOrDefault(u => u.Login == name);
                return user != null && user.IsAdmin;
            }
        }
    }
}